package com.pm.util;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class DatabaseInitializer {
    public static void main(String[] args) {
        String dbPath = "database/pm.db";
        String sqlFilePath = "src/main/resources/data.sql";
        
        try {
            // Read SQL file content
            String sqlContent = new String(Files.readAllBytes(Paths.get(sqlFilePath)));
            
            // Connect to SQLite database
            Connection conn = DriverManager.getConnection("jdbc:sqlite:" + dbPath);
            Statement stmt = conn.createStatement();
            
            // Split and execute SQL statements
            String[] sqlStatements = sqlContent.split(";");
            
            for (String sql : sqlStatements) {
                sql = sql.trim();
                if (!sql.isEmpty() && !sql.startsWith("--") && !sql.startsWith("SELECT 'Database")) {
                    try {
                        stmt.execute(sql);
                        System.out.println("Executed: " + sql.substring(0, Math.min(50, sql.length())) + "...");
                    } catch (Exception e) {
                        System.err.println("Error executing: " + sql.substring(0, Math.min(50, sql.length())));
                        System.err.println("Error: " + e.getMessage());
                    }
                }
            }
            
            stmt.close();
            conn.close();
            
            System.out.println("Database initialization completed successfully!");
            
        } catch (IOException e) {
            System.err.println("Error reading SQL file: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("Database error: " + e.getMessage());
        }
    }
}